今天要修改一下我們的資料架構,新增一張types的表,紀錄文章的類別,然後在原先的posts表,新增一個type欄位,來紀錄文章類別的關聯。
原先,我們在console執行了這條去創造我們的model
rails generate model Post title:string content:text
他會在/db/migrate資料夾中,去生成一個產生我們的資料表的migration檔案。
然後我們又執行了rails db:migrate去依照這個檔案生成資料表。
如今,我們要重新去訂我們的資料表,我想依序做兩件事:
細節就不贅述了,可以去參考rails的系列文章或是高見龍的為你自己學ruby and rails裡面都有更詳細的內容
以下是我的migration檔
class CreatePostsAndTypes < ActiveRecord::Migration[6.0]
  def change
    drop_table :posts
    
    create_table :posts do |t|
      t.string :title
      t.text :content
      t.datetime :deleted_at
      t.references :type, polymorphic: true, index: true
      t.timestamps
    end
    
    create_table :types do |t|
      t.string :name
      t.timestamps
    end
  end
end
以及他們的model:
class Post < ApplicationRecord
    belongs_to :type
    
    # 只抓deleted_at為被設定的文章
    default_scope { where(deleted_at: nil) }
    # 在文章destroy的時候不會真正刪除,而是設定他的deleted_at
    def destroy
      update(deleted_at: Time.now)
    end    
end
class Type < ApplicationRecord
    has_many :posts
end
然後在console執行rails db:migrate,就能做好我們要的資料表結構了。
接著,在console執行rails c,開啟rails 的執行環境,執行:
=>Type.create!(name:"生活")
=>Type.create!(name:"技術")
=>Type.create!(name:"旅遊")
=>Post.create!(title: "title1", content: "content1", type: Type.find(1)) #新增一則生活文章
=>Post.create!(title: "title2", content: "content2", type: Type.find(2)) #新增一則技術文章
=>Post.create!(title: "title3", content: "content3", type: Type.find(3)) #新增一則旅遊文章
=>Post.create!(title: "title4", content: "content4", type: Type.find(3)) #新增一則旅遊文章
這樣我們的文章就建立好了。